from time import sleep
import re
from qturboframe.lib.utils.by import By
from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.public_ui.base_element import BaseElement


class Ul(BaseElement, CheckBasic):
    '''ul标签'''

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)


    def select(self, link_text, index=1, selected_sign = ['h-menu-item-selected','h-menu-opened']):
        '''
        选择节点

        :Args:
         - link_text: 节点的文字
         - index：控件的索引
         - selected_sign：用来标记节点是否被选择的标记

        :Raises:
            SeleniumError: 菜单操作失败

        :Example:
         - 例: ul.select('一级菜单')
         - 例: ul.select('一级菜单',selected_sign = 'h-menu-item-selected123')
        '''
        li_xpath = ".//li[normalize-space(string())='{}']".format(link_text)
        elements = self.element.find_elements_by_attribute(By.XPATH, li_xpath, timeout=self.timeout)
        visible_elements = []
        for e in elements:
            if e.is_displayed():
                visible_elements.append(e)



        up_ul = self._element.find_element_by_attribute('xpath', './ul', timeout=self.timeout)
        value_list = link_text.split('/')
        for va in value_list:
            if up_ul is not None:
                up_ul = self.__click_node_by_nodename(up_ul, va)

    def __click_node_by_nodename(self, up_ul, value):
        ul = None
        re_open_li = r'h-menu-opened'
        re_item_li = r'h-menu-item'
        re_selected_li = r'h-menu-item-selected'
        lis = up_ul.find_elements_by_attribute('xpath', './*/li', timeout=self.timeout)
        for li in lis:
            li_class = li.get_attribute('class')
            if re_item_li == li_class or re_selected_li in li_class:
                if li.find_element_by_attribute('xpath', './span',
                                                timeout=self.timeout).text == value:
                    logger.info('打开菜单：' + value)
                    li.find_element_by_attribute('xpath', './span').secure_click()
                    break
            else:
                if li.find_element_by_attribute('xpath', './div',
                                                timeout=self.timeout).text == value:
                    if not re.search(re_open_li, li_class):
                        logger.info('打开菜单：' + value)
                        li.find_element_by_attribute('xpath:./div/span').secure_click()
                    ul = li.exist('xpath:./ul', timeout=self.timeout)
                    break
        return ul


